<template>
  <div class="trace-detail-view">
    <!-- 顶部基本信息 -->
    <div class="header">
      <img :src="detail.url" class="cover" />
      <div class="base-info">
        <div class="title-row">
          <h2>{{ detail.sName }}</h2>
          <div class="header-actions">
            <el-button size="small">修改基本信息</el-button>
            <el-button size="small">导出溯源码</el-button>
          </div>
        </div>
        <div class="info-row">
          <span>生产批次：{{ detail.batch }}</span>
          <span>保质期：{{ detail.expiration_date }}天</span>
          <span>生产许可证号：{{ detail.production_License }}</span>
          <span>生产企业：{{ detail.manufacturing_Enterprises }}</span>
        </div>
      </div>
    </div>
    <!-- 检测报告 -->
    <div class="section">
      <div class="section-title">产品检测报告</div>
      <div class="image-upload-grid">
        <template v-for="(item, index) in imageGroups[getImageKey(1, 1)]" :key="item.id">
          <div class="image-item">
            <img :src="item.displayUrl" class="image-preview" />
            <div class="image-actions">
              <el-icon class="delete-icon" @click="handleDeleteImage(1, 1, index, item.id)">
                <Delete />
              </el-icon>
            </div>
          </div>
        </template>
        <el-upload v-if="(imageGroups[getImageKey(1, 1)] || []).length < 9" class="image-uploader" action="#"
          :show-file-list="false" :auto-upload="false" :on-change="(file: UploadFile) => handleImageChange(file, 1, 1)"
          name="file">
          <div class="image-upload-box">
            <i class="el-icon-plus upload-icon"></i>
            <span class="upload-text">+</span>
          </div>
        </el-upload>
      </div>
    </div>
    <!-- 标签页 -->
    <el-tabs v-model="activeTab">
      <el-tab-pane label="养殖信息" name="base">
        <div v-if="activeTab === 'base'">
          <!-- 养殖信息部分 -->
          <div class="section">
            <div class="section-title">
              养殖信息
              <el-button size="small" @click="showFarmingDialog = true">设置</el-button>
            </div>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="品种">{{ detail.variety }}</el-descriptions-item>
              <el-descriptions-item label="来源">{{ detail.source }}</el-descriptions-item>
              <el-descriptions-item label="饲养天数">{{ detail.feeding_Date }}</el-descriptions-item>
              <el-descriptions-item label="饲料品种">{{ detail.feed_Brand }}</el-descriptions-item>
              <el-descriptions-item label="饲养负责人">{{ detail.animal_Caretaker }}</el-descriptions-item>
              <el-descriptions-item label="出栏日期">{{ moment(detail.departure).format("yyyy年MM月DD日")
              }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 保健信息部分 -->
          <div class="section">
            <div class="health-info-header">
              <div class="header-content">
                <div class="title">保健信息</div>
                <div class="add-button" @click="addNewRow">
                  新增行
                  <div class="badge">{{ healthList.length }}</div>
                </div>
              </div>
            </div>

            <el-table :data="healthList" border style="width: 100%">
              <el-table-column prop="feeding_Date" label="饲养天数" width="180">
                <template #default="scope">
                  <el-input v-if="scope.row.isNew || scope.row.editing" v-model.number="scope.row.feeding_Date"
                    type="number" placeholder="请输入饲养天数" class="no-border" />
                  <span v-else>{{ scope.row.feeding_Date }}</span>
                </template>
              </el-table-column>

              <el-table-column prop="health_Products" label="保健方式" min-width="200">
                <template #default="scope">
                  <el-input v-if="scope.row.isNew || scope.row.editing" v-model="scope.row.health_Products"
                    placeholder="请输入保健方式" class="no-border" />
                  <span v-else>{{ scope.row.health_Products }}</span>
                </template>
              </el-table-column>

              <el-table-column prop="healthcare_Methods" label="保健方法" min-width="200">
                <template #default="scope">
                  <el-input v-if="scope.row.isNew || scope.row.editing" v-model="scope.row.healthcare_Methods"
                    placeholder="请输入保健方法" class="no-border" />
                  <span v-else>{{ scope.row.healthcare_Methods }}</span>
                </template>
              </el-table-column>

              <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                  <div class="operation-buttons">
                    <template v-if="scope.row.isNew">
                      <el-button type="primary" link @click="onSaveNewRow(scope.row)"
                        :disabled="!isValidRow(scope.row)">保存</el-button>
                      <el-button link @click="onCancelNewRow(scope.$index)">取消</el-button>
                    </template>
                    <template v-else-if="scope.row.editing">
                      <el-button type="primary" link @click="onSaveRow(scope.row)"
                        :disabled="!isValidRow(scope.row)">保存</el-button>
                      <el-button link @click="onCancelEdit(scope.row)">取消</el-button>
                    </template>
                    <template v-else>
                      <div class="action-group">

                        <el-button type="primary" link @click="onEditRow(scope.row)">修改</el-button>

                        <el-button type="danger" link @click="onDeleteRow(scope.$index)">删除</el-button>
                      </div>
                    </template>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 动检证 -->
          <div class="section">
            <div class="section-title">动检证</div>
            <div class="image-upload-grid">
              <template v-for="(item, index) in imageGroups[getImageKey(1, 2)]" :key="item.id">
                <div class="image-item">
                  <img :src="item.displayUrl" class="image-preview" />
                  <div class="image-actions">
                    <el-icon class="delete-icon" @click="handleDeleteImage(1, 2, index, item.id)">
                      <Delete />
                    </el-icon>
                  </div>
                </div>
              </template>
              <el-upload v-if="(imageGroups[getImageKey(1, 2)] || []).length < 9" class="image-uploader" action="#"
                :show-file-list="false" :auto-upload="false"
                :on-change="(file: UploadFile) => handleImageChange(file, 1, 2)" name="file">
                <div class="image-upload-box">
                  <i class="el-icon-plus upload-icon"></i>
                  <span class="upload-text">+</span>
                </div>
              </el-upload>
            </div>
          </div>
          <!-- 企业信息 -->
          <div class="section">
            <div class="section-title">
              企业信息
              <el-button size="small" @click="showFarmingCompanyDialog = true">设置</el-button>
            </div>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="养殖场">{{ farmInfo.aquaculture_Enterprise }}</el-descriptions-item>
              <el-descriptions-item label="负责人">{{ farmInfo.principal }}</el-descriptions-item>
              <el-descriptions-item label="存栏数量">{{ farmInfo.survival_Number }}只</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 养殖企业信息设置弹窗 -->
          <el-dialog v-model="showFarmingCompanyDialog" title="企业信息" width="500px">
            <el-form :model="farmingForm" :rules="farmRules" ref="farmingCompanyFormRef" label-width="120px">
              <el-form-item label="养殖场：" prop="aquaculture_Enterprise">
                <el-input v-model="farmingForm.aquaculture_Enterprise" maxlength="30" show-word-limit />
              </el-form-item>
              <el-form-item label="负责人：" prop="principal">
                <el-input v-model="farmingForm.principal" maxlength="20" show-word-limit />
              </el-form-item>
              <el-form-item label="存栏数量（只）：" prop="survival_Number">
                <el-input-number v-model="farmingForm.survival_Number" :min="0" :max="99999" />
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="showFarmingCompanyDialog = false">取消</el-button>
                <el-button type="primary" @click="saveFarmInfo">保存</el-button>
              </span>
            </template>
          </el-dialog>
          <!-- 企业照片 -->
          <div class="section">
            <div class="section-title">企业照片</div>
            <div class="image-upload-grid">
              <template v-for="(item, index) in imageGroups[getImageKey(1, 3)]" :key="item.id">
                <div class="image-item">
                  <img :src="item.displayUrl" class="image-preview" />
                  <div class="image-actions">
                    <el-icon class="delete-icon" @click="handleDeleteImage(1, 3, index, item.id)">
                      <Delete />
                    </el-icon>
                  </div>
                </div>
              </template>
              <el-upload v-if="(imageGroups[getImageKey(1, 3)] || []).length < 9" class="image-uploader" action="#"
                :show-file-list="false" :auto-upload="false"
                :on-change="(file: UploadFile) => handleImageChange(file, 1, 3)" name="file">
                <div class="image-upload-box">
                  <i class="el-icon-plus upload-icon"></i>
                  <span class="upload-text">+</span>
                </div>
              </el-upload>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="屠宰信息" name="slaughter">
        <div v-if="activeTab === 'slaughter'">
          <!-- 屠宰信息展示 -->
          <div class="section">
            <div class="section-title">
              屠宰信息
              <el-button size="small" @click="showSlaughterDialog = true">设置</el-button>
            </div>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="批次">{{ slaughterDetail.batch }}</el-descriptions-item>
              <el-descriptions-item label="到厂均重">{{ slaughterDetail.weight }} 公斤</el-descriptions-item>
              <el-descriptions-item label="到厂时间">{{ slaughterDetail.arrive_Time ?
                moment(slaughterDetail.arrive_Time).format("YYYY年MM月DD日 HH:mm:ss") : '' }}</el-descriptions-item>
              <el-descriptions-item label="屠宰时间">{{ slaughterDetail.slaughtering_Time ?
                moment(slaughterDetail.slaughtering_Time).format("YYYY年MM月DD日 HH:mm:ss") : '' }}</el-descriptions-item>
            </el-descriptions>
          </div>
          <!-- 相关资质 -->
          <div class="section">
            <div class="section-title">相关资质</div>
            <div class="image-upload-grid">
              <template v-for="(item, index) in imageGroups[getImageKey(2, 2)]" :key="item.id">
                <div class="image-item">
                  <img :src="item.displayUrl" class="image-preview" />
                  <div class="image-actions">
                    <el-icon class="delete-icon" @click="handleDeleteImage(2, 2, index, item.id)">
                      <Delete />
                    </el-icon>
                  </div>
                </div>
              </template>
              <el-upload v-if="(imageGroups[getImageKey(2, 2)] || []).length < 9" class="image-uploader" action="#"
                :show-file-list="false" :auto-upload="false"
                :on-change="(file: UploadFile) => handleImageChange(file, 2, 2)" name="file">
                <div class="image-upload-box">
                  <i class="el-icon-plus upload-icon"></i>
                  <span class="upload-text">+</span>
                </div>
              </el-upload>
            </div>
          </div>
          <!-- 企业信息 -->
          <div class="section">
            <div class="section-title">
              企业信息
              <el-button size="small" @click="showSlaughterCompanyDialog = true">设置</el-button>
            </div>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="公司名称">{{ slaughterCompany.slaughter_Enterprise }}</el-descriptions-item>
              <el-descriptions-item label="成立时间">{{ slaughterCompany.founding_Time ?
                moment(slaughterCompany.founding_Time).format("yyyy年MM月DD日") : '' }}</el-descriptions-item>
              <el-descriptions-item label="公司地址">
                <!-- 只使用一个RegionText组件，并通过slaughterRegion提供正确格式的数据 -->
                <RegionText v-model="slaughterRegion" separator=" " />
                <!-- <div style="margin-top: 5px; color: #999; font-size: 12px;">
                  (原始代码: {{ slaughterCompany.province || '-' }} {{ slaughterCompany.city || '-' }} {{
                    slaughterCompany.county || '-' }})
                  <el-button type="text" size="small" @click="refreshAddress">刷新地址</el-button>
                </div> -->
              </el-descriptions-item>
              <el-descriptions-item label="公司简介" :span="2">{{ slaughterCompany.company_Profile }}</el-descriptions-item>
            </el-descriptions>
          </div>
          <!-- 企业照片 -->
          <div class="section">
            <div class="section-title">企业照片</div>
            <div class="image-upload-grid">
              <template v-for="(item, index) in imageGroups[getImageKey(2, 3)]" :key="item.id">
                <div class="image-item">
                  <img :src="item.displayUrl" class="image-preview" />
                  <div class="image-actions">
                    <el-icon class="delete-icon" @click="handleDeleteImage(2, 3, index, item.id)">
                      <Delete />
                    </el-icon>
                  </div>
                </div>
              </template>
              <el-upload v-if="(imageGroups[getImageKey(2, 3)] || []).length < 9" class="image-uploader" action="#"
                :show-file-list="false" :auto-upload="false"
                :on-change="(file: UploadFile) => handleImageChange(file, 2, 3)" name="file">
                <div class="image-upload-box">
                  <i class="el-icon-plus upload-icon"></i>
                  <span class="upload-text">+</span>
                </div>
              </el-upload>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="深加工信息" name="process">
        <div v-if="activeTab === 'process'">
          <!-- 深加工信息展示 -->
          <div class="section">
            <div class="section-title">
              深加工信息
              <el-button size="small" @click="showProcessDialog = true">设置</el-button>
            </div>
            <div>班组：{{ processDetail.responsible_Team }} &nbsp;&nbsp; 负责人：{{ processDetail.principal }}</div>
          </div>
          <!-- 食品安全信息 -->
          <div class="section">
            <div class="section-title">食品安全信息</div>
            <div class="image-upload-grid">
              <template v-for="(item, index) in imageGroups[getImageKey(3, 4)]" :key="item.id">
                <div class="image-item">
                  <img :src="item.displayUrl" class="image-preview" />
                  <div class="image-actions">
                    <el-icon class="delete-icon" @click="handleDeleteImage(3, 4, index, item.id)">
                      <Delete />
                    </el-icon>
                  </div>
                </div>
              </template>
              <el-upload v-if="(imageGroups[getImageKey(3, 4)] || []).length < 9" class="image-uploader" action="#"
                :show-file-list="false" :auto-upload="false"
                :on-change="(file: UploadFile) => handleImageChange(file, 3, 4)" name="file">
                <div class="image-upload-box">
                  <i class="el-icon-plus upload-icon"></i>
                  <span class="upload-text">+</span>
                </div>
              </el-upload>
            </div>
          </div>
          <!-- 供应商信息：原料、辅料、添加剂、包装 -->
          <div v-for="(supplier, idx) in processSuppliers" :key="idx" class="section">
            <div class="section-title">
              {{ supplier.label }}
              <el-button size="small" @click="openSupplierDialog(idx)">设置</el-button>
            </div>
            <div>生产批次：{{ supplier.batch }}</div>
            <div class="section-title" style="margin-top: 8px;">相关材料</div>
            <div class="image-upload-grid">
              <template v-for="(item, index) in imageGroups[getImageKey(3, 5 + idx)]" :key="item.id">
                <div class="image-item">
                  <img :src="item.displayUrl" class="image-preview" />
                  <div class="image-actions">
                    <el-icon class="delete-icon" @click="handleDeleteImage(3, 5 + idx, index, item.id)">
                      <Delete />
                    </el-icon>
                  </div>
                </div>
              </template>
              <el-upload v-if="(imageGroups[getImageKey(3, 5 + idx)] || []).length < 9" class="image-uploader"
                action="#" :show-file-list="false" :auto-upload="false"
                :on-change="(file: UploadFile) => handleImageChange(file, 3, 5 + idx)" name="file">
                <div class="image-upload-box">
                  <i class="el-icon-plus upload-icon"></i>
                  <span class="upload-text">+</span>
                </div>
              </el-upload>
            </div>
          </div>
          <!-- 企业信息 -->
          <div class="section" style="border: 1px solid #f0f0f0; padding: 16px; margin-bottom: 20px;">
            <div class="section-title">
              企业信息
              <el-button size="small" @click="showProcessingPlantDialog = true">设置</el-button>
            </div>
            <div style="display: flex; margin-top: 10px;">
              <div style="width: 50%; display: flex;">
                <span style="width: 100px; text-align: right; margin-right: 10px;">公司名称：</span>
                <span>{{ processingPlant.deep_Enterprise }}</span>
              </div>
              <div style="width: 50%; display: flex;">
                <span style="width: 100px; text-align: right; margin-right: 10px;">生产许可证号：</span>
                <span>{{ processingPlant.production_Permit }}</span>
              </div>
            </div>
          </div>
          <!-- 企业照片 -->
          <div class="section">
            <div class="section-title">企业照片</div>
            <div class="image-upload-grid">
              <template v-for="(item, index) in imageGroups[getImageKey(3, 3)]" :key="item.id">
                <div class="image-item">
                  <img :src="item.displayUrl" class="image-preview" />
                  <div class="image-actions">
                    <el-icon class="delete-icon" @click="handleDeleteImage(3, 3, index, item.id)">
                      <Delete />
                    </el-icon>
                  </div>
                </div>
              </template>
              <el-upload v-if="(imageGroups[getImageKey(3, 3)] || []).length < 9" class="image-uploader" action="#"
                :show-file-list="false" :auto-upload="false"
                :on-change="(file: UploadFile) => handleImageChange(file, 3, 3)" name="file">
                <div class="image-upload-box">
                  <i class="el-icon-plus upload-icon"></i>
                  <span class="upload-text">+</span>
                </div>
              </el-upload>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- 养殖信息设置弹窗 -->
    <el-dialog v-model="showFarmingDialog" title="养殖信息11" width="500px">
      <el-form :model="farmingDetail" :rules="farmingRules" ref="farmingFormRef" label-width="110px">
        <el-form-item label="品种：" prop="variety" required>
          <el-input v-model="farmingDetail.variety" />
        </el-form-item>
        <el-form-item label="来源：" prop="source" required>
          <el-input v-model="farmingDetail.source" />
        </el-form-item>
        <el-form-item label="饲养天数：" prop="feeding_Date" required>
          <el-input v-model="farmingDetail.feeding_Date" />
        </el-form-item>
        <el-form-item label="饲料品牌：" prop="feed_Brand" required>
          <el-input v-model="farmingDetail.feed_Brand" />
        </el-form-item>
        <el-form-item label="饲养负责人：" prop="animal_Caretaker" required>
          <el-input v-model="farmingDetail.animal_Caretaker" />
        </el-form-item>
        <el-form-item label="出栏日期：" prop="departure" required>
          <el-date-picker v-model="farmingDetail.departure" type="date" value-format="YYYY-MM-DD" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="queryRegion">取消</el-button>
        <el-button type="primary" @click="onSaveFarming">保存</el-button>
      </template>
    </el-dialog>
    <!-- 屠宰信息设置弹窗（参考第二张图片） -->
    <el-dialog v-model="showSlaughterDialog" title="屠宰信息" width="500px">
      <el-form :model="slaughterForm" :rules="slaughterRules" ref="slaughterFormRef" label-width="110px">
        <el-form-item label="批次：" prop="batch" required>
          <el-input v-model="slaughterForm.batch" />
        </el-form-item>
        <el-form-item label="到厂均重（公斤）：" prop="weight" required>
          <el-input v-model="slaughterForm.weight" />
        </el-form-item>
        <el-form-item label="到厂时间：" prop="arrive_Time" required>
          <el-date-picker v-model="slaughterForm.arrive_Time" type="datetime" format="YYYY年MM月DD日 HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择到厂时间" />
        </el-form-item>
        <el-form-item label="屠宰时间：" prop="slaughtering_Time" required>
          <el-date-picker v-model="slaughterForm.slaughtering_Time" type="datetime" format="YYYY年MM月DD日 HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择屠宰时间" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showSlaughterDialog = false">取消</el-button>
        <el-button type="primary" @click="onSaveSlaughter">保存</el-button>
      </template>
    </el-dialog>
    <!-- 屠宰企业信息设置弹窗（参考第三张图片） -->
    <el-dialog v-model="showSlaughterCompanyDialog" title="企业信息" width="500px">
      <el-form :model="slaughterCompanyForm" :rules="slaughterCompanyRules" ref="slaughterCompanyFormRef"
        label-width="110px">
        <el-form-item label="公司名称：" prop="slaughter_Enterprise" required>
          <el-input v-model="slaughterCompanyForm.slaughter_Enterprise" />
        </el-form-item>
        <el-form-item label="公司地址：" required>
          <RegionSelects v-model="slaughterRegion" />
        </el-form-item>
        <el-form-item label="成立时间：" prop="founding_Time" required>
          <el-date-picker v-model="slaughterCompanyForm.founding_Time" type="date" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="公司简介：" prop="company_Profile" required>
          <el-input v-model="slaughterCompanyForm.company_Profile" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showSlaughterCompanyDialog = false">取消</el-button>
        <el-button type="primary" @click="onSaveSlaughterCompany">保存</el-button>
      </template>
    </el-dialog>
    <!-- 深加工信息设置弹窗 -->
    <el-dialog v-model="showProcessDialog" title="深加工信息" width="400px">
      <el-form :model="processForm" :rules="processRules" ref="processFormRef" label-width="90px">
        <el-form-item label="班组：" prop="responsible_Team" required>
          <el-input v-model="processForm.responsible_Team" />
        </el-form-item>
        <el-form-item label="负责人：" prop="principal" required>
          <el-input v-model="processForm.principal" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showProcessDialog = false">取消</el-button>
        <el-button type="primary" @click="onSaveProcess">保存</el-button>
      </template>
    </el-dialog>
    <!-- 深加工企业信息设置弹窗 -->
    <el-dialog v-model="showProcessingPlantDialog" title="企业信息" width="400px">
      <el-form :model="processingPlantForm" :rules="processingPlantRules" ref="processingPlantFormRef"
        label-width="90px">
        <el-form-item label="公司名称：" prop="deep_Enterprise" required>
          <el-input v-model="processingPlantForm.deep_Enterprise" />
        </el-form-item>
        <el-form-item label="生产许可证号：" prop="production_Permit" required>
          <el-input v-model="processingPlantForm.production_Permit" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showProcessingPlantDialog = false">取消</el-button>
        <el-button type="primary" @click="onSaveProcessingPlant">保存</el-button>
      </template>
    </el-dialog>
    <!-- 供应商信息设置弹窗 -->
    <el-dialog v-model="showSupplierDialog" :title="supplierDialogTitle" width="400px">
      <el-form :model="supplierForm" :rules="supplierRules" ref="supplierFormRef" label-width="90px">
        <el-form-item label="生产批次：" prop="batch" required>
          <el-input v-model="supplierForm.batch" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showSupplierDialog = false">取消</el-button>
        <el-button type="primary" @click="onSaveSupplier">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import moment from 'moment'
import { Delete, Plus, Edit } from '@element-plus/icons-vue'
import { source, fileUpload } from '@/http/axiosHelper'
import type { UploadFile } from 'element-plus'
import { RegionSelects, RegionText } from 'v-region'
import type { RegionValues } from 'v-region'
import type { FormInstance } from 'element-plus'

// 保健信息接口
interface HealthInfo {
  id?: number;
  feeding_Date: number;         // 修改为数字类型
  health_Products: string;      // 保健方式
  healthcare_Methods: string;   // 保健方法
  editing?: boolean;
  batch?: string;
  createUserId?: number;
  originalData?: {
    feeding_Date: number;
    health_Products: string;
    healthcare_Methods: string;
  };
  isNew?: boolean; // 新增的属性
}

interface ApiResponse {
  code: number;
  data: any;
  msg?: string;
}

const route = useRoute()
const activeTab = ref('base')
const healthList = ref<HealthInfo[]>([])
const isAdding = ref(false)

// 新行数据
const newRow = reactive<HealthInfo>({
  feeding_Date: 0,
  health_Products: '',
  healthcare_Methods: '',
  batch: '',
  createUserId: 0
})

// 开始添加新行
function addNewRow() {
  const newRowData = {
    feeding_Date: 0,
    health_Products: '',
    healthcare_Methods: '',
    isNew: true
  };
  healthList.value.push(newRowData); // 改用 push 添加到底部
}

// 取消添加
function cancelAdd() {
  isAdding.value = false
}

// 获取保健信息列表
async function fetchHealthList() {
  try {
    const res = await source.get('/api/Aquaculture/HealthcareGet', {
      params: {
        batch: detail.value.batch
      }
    })
    if (res.data.code === 200) {
      healthList.value = res.data.data.map((item: any) => ({
        ...item,
        editing: false
      }))
    }
  } catch (error) {
    console.error('获取保健信息失败:', error)
    ElMessage.error('获取保健信息失败')
  }
}

// 添加新行
async function onAddRow() {
  if (!newRow.feeding_Date || !newRow.health_Products || !newRow.healthcare_Methods) {
    ElMessage.warning('请填写完整信息')
    return
  }

  try {
    const res = await source.post('/api/Aquaculture/HealthcareAdd', {
      batch: detail.value.batch,
      feeding_Date: Number(newRow.feeding_Date),
      health_Products: newRow.health_Products,
      healthcare_Methods: newRow.healthcare_Methods,
      createUserId: Number(localStorage.getItem("id"))
    })

    if (res.data.code === 200) {
      // 添加到列表
      healthList.value.push({
        id: res.data.data.id,
        feeding_Date: Number(newRow.feeding_Date),
        health_Products: newRow.health_Products,
        healthcare_Methods: newRow.healthcare_Methods,
        editing: false
      })

      // 清空输入
      newRow.feeding_Date = 0
      newRow.health_Products = ''
      newRow.healthcare_Methods = ''

      ElMessage.success('添加成功')

    } else {
      ElMessage.error(res.data.msg || '添加失败')
    }
  } catch (error) {
    console.error('添加保健信息失败:', error)
    ElMessage.error('添加失败')
  }
}

// 开始编辑行
function onEditRow(row: HealthInfo) {
  row.editing = true
}

// 保存编辑
async function onSaveRow(row: HealthInfo) {
  if (!row.feeding_Date || !row.health_Products || !row.healthcare_Methods) {
    ElMessage.warning('请填写完整信息')
    return
  }

  try {
    const res = await source.post('/api/Aquaculture/HealthcareUp', {
      id: row.id,
      batch: detail.value.batch,
      feeding_Date: Number(row.feeding_Date),
      health_Products: row.health_Products,
      healthcare_Methods: row.healthcare_Methods,
      createUserId: Number(localStorage.getItem("id"))
    })

    if (res.data.code === 200) {
      row.editing = false
      delete row.originalData // 清除临时数据
      ElMessage.success('保存成功')
      await fetchHealthList();

    } else {
      ElMessage.error(res.data.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存保健信息失败:', error)
    ElMessage.error('保存失败')
  }
}

// 删除行
async function onDeleteRow(index: number) {
  const row = healthList.value[index]
  if (!row.id) {
    ElMessage.error('无法删除未保存的数据');
    return;
  }

  try {
    const res = await source.post('/api/Aquaculture/HealthcareDel', null, {
      params: {
        Id: row.id
      }
    })


    if (res.data.code === 200) {

      healthList.value.splice(index, 1)
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除保健信息失败:', error)
    ElMessage.error('删除失败')
  }
}

// 取消编辑
function onCancelEdit(row: HealthInfo) {
  if (row.originalData) {
    row.feeding_Date = row.originalData.feeding_Date
    row.health_Products = row.originalData.health_Products
    row.healthcare_Methods = row.originalData.healthcare_Methods
  }
  row.editing = false
}

// 验证行数据
function isValidRow(row: HealthInfo) {
  return row.feeding_Date > 0 &&
    row.health_Products?.trim() !== '' &&
    row.healthcare_Methods?.trim() !== '';
}

const detail = ref({
  url: '',
  sName: '',
  batch: '',
  expiration_date: '',
  production_License: '',
  manufacturing_Enterprises: '',
  reports: [],
  id: 0,
  variety: '',
  source: '',
  feeding_Date: '',
  feed_Brand: '',
  animal_Caretaker: '',
  departure: '',
  createUserId: 0,
  healthList: [],
  animalCerts: [],
  companyName: '',
  companyManager: '',
  companyCount: '',
  companyPhotos: []
})
// ================== 养殖信息 ==================
// 养殖企业相关类型定义
interface FarmInfo {
  id?: number
  batch?: string
  aquaculture_Enterprise: string
  principal: string
  survival_Number: number
  createUserId?: number
}

interface FarmingDetail {
  id: number
  batch: string
  variety: string
  source: string
  feeding_Date: string
  feed_Brand: string
  animal_Caretaker: string
  departure: string
  createUserId: string | null
  aquaculture_Enterprise: string
  principal: string
  survival_Number: number
}

// 养殖企业相关数据
const showFarmingCompanyDialog = ref(false)
const showFarmingDialog = ref(false)
const farmingCompanyFormRef = ref<FormInstance>()
const farmingFormRef = ref<FormInstance>()

const farmInfo = ref<FarmInfo>({
  aquaculture_Enterprise: '',
  principal: '',
  survival_Number: 0
})

const farmingForm = ref<FarmInfo>({
  aquaculture_Enterprise: '',
  principal: '',
  survival_Number: 0
})

const farmingDetail = ref<FarmingDetail>({
  id: 0,
  batch: '',
  variety: '',
  source: '',
  feeding_Date: '',
  feed_Brand: '',
  animal_Caretaker: '',
  departure: '',
  createUserId: null,
  aquaculture_Enterprise: '',
  principal: '',
  survival_Number: 0
})

// 养殖企业表单验证规则
const farmRules = {
  aquaculture_Enterprise: [
    { required: true, message: '请输入养殖场名称', trigger: 'blur' },
    { max: 30, message: '长度不能超过30个字符', trigger: 'blur' }
  ],
  principal: [
    { required: true, message: '请输入负责人', trigger: 'blur' },
    { max: 20, message: '长度不能超过20个字符', trigger: 'blur' }
  ],
  survival_Number: [
    { required: true, message: '请输入存栏数量', trigger: 'blur' },
    { type: 'number', min: 0, max: 99999, message: '数量必须在0-99999之间', trigger: 'blur' }
  ]
}

// 养殖信息表单验证规则
const farmingRules = {
  variety: [{ required: true, message: '请输入品种', trigger: 'blur' }],
  source: [{ required: true, message: '请输入来源', trigger: 'blur' }],
  feeding_Date: [{ required: true, message: '请输入饲养天数', trigger: 'blur' }],
  feed_Brand: [{ required: true, message: '请输入饲料品牌', trigger: 'blur' }],
  animal_Caretaker: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  departure: [{ required: true, message: '请选择出栏日期', trigger: 'change' }]
}


// 保存养殖企业信息
const saveFarmInfo = async () => {
  if (!farmingCompanyFormRef.value) return

  await farmingCompanyFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const formData = {
          ...farmingForm.value,
          batch: detail.value.batch,
          createUserId: Number(localStorage.getItem("id"))
        }


        const response = await source.post('/api/Aquaculture/FarmAdd', formData)

        if (response.data.code === 200) {
          ElMessage.success('保存成功')
          showFarmingCompanyDialog.value = false

          // 立即更新显示数据
          Object.assign(farmInfo.value, farmingForm.value)

          // 重新获取最新数据
          await getFarmInfo()
        } else {
          ElMessage.error(response.data.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存养殖企业信息失败:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}

// 获取养殖企业信息
const getFarmInfo = async () => {
  try {

    const response = await source.get('/api/Aquaculture/FarmQuery', {
      params: {
        Batch: detail.value.batch
      }
    })

    if (response.data.code === 200) {


      const data = response.data.data
      // 更新显示数据
      Object.assign(farmInfo.value, data)
      // 更新表单数据
      Object.assign(farmingForm.value, data)
    }
  } catch (error) {
    console.error('获取养殖企业信息失败:', error)
    ElMessage.error('获取企业信息失败')
  }
}


const queryRegion = () => {

  showFarmingDialog.value = false
  fetchFarmingInfo()

}


// 获取养殖信息
const fetchFarmingInfo = async () => {
  try {
    const response = await source.get('/api/Aquaculture/AquacultureShow', {
      params: {
        Batch: detail.value.batch
      }
    })

    if (response.data.code === 200) {
      const data = response.data.data
      // 更新养殖信息
      Object.assign(farmingDetail.value, data)
      Object.assign(detail.value, data)


    }
  } catch (error) {
    console.error('获取养殖信息失败:', error)
    ElMessage.error('获取养殖信息失败')
  }
}

// 监听标签页切换
watch(activeTab, async (val) => {
  if (val === 'base') {
    await fetchFarmingInfo()
    await getFarmInfo()

    await fetchImages(1, 2) // 动检证
    await fetchImages(1, 3) // 企业照片
    // 保健信息图片
    await fetchImages(1, 4) // 保健信息
  } else if (val === 'slaughter' && detail.value.batch) {
    await fetchSlaughterInfo()
    await getSlaughterCompanyInfo()

    // 屠宰信息图片
    await fetchImages(2, 2) // 相关资质
    await fetchImages(2, 3) // 企业照片

  } else if (val === 'process' && detail.value.batch) {
    await fetchProcessingPlant() // 获取深加工企业信息
    await fetchProcessDetail() // 获取深加工信息
    /* supplierForm.batch = detail.value.batch */

    // 深加工信息图片
    await fetchImages(3, 4) // 食品安全信息
    await fetchImages(3, 3) // 企业照片

    // 供应商信息图片
    await fetchImages(3, 5) // 原料
    await fetchImages(3, 6) // 辅料
    await fetchImages(3, 7) // 添加剂
    await fetchImages(3, 8) // 包装

    for (let i = 0; i <= 3; i++) {
      processSuppliers.value[i].batch = detail.value.batch;
    }
  }
})

// 在组件挂载时获取养殖企业信息
onMounted(async () => {
  await TracebackDetail() // 先拿到 batch
  if (activeTab.value === 'base') {
    await fetchFarmingInfo()
    await fetchHealthList()
    await getFarmInfo()

    await fetchImages(1, 2) // 动检证
    await fetchImages(1, 3) // 企业照片
    // 保健信息图片
    await fetchImages(1, 4) // 保健信息

  } else if (activeTab.value === 'slaughter' && detail.value.batch) {
    await fetchSlaughterInfo()
    await getSlaughterCompanyInfo() // 获取屠宰企业信息

    // 屠宰信息图片
    await fetchImages(2, 2) // 相关资质
    await fetchImages(2, 3) // 企业照片
  } else if (activeTab.value === 'process' && detail.value.batch) {
    await fetchProcessingPlant() // 获取深加工企业信息
    await fetchProcessDetail() // 获取深加工信息

    // 深加工信息图片
    await fetchImages(3, 4) // 食品安全信息
    await fetchImages(3, 3) // 企业照片

    // 供应商信息图片
    await fetchImages(3, 5) // 原料
    await fetchImages(3, 6) // 辅料
    await fetchImages(3, 7) // 添加剂
    await fetchImages(3, 8) // 包装





  }
  // 养殖信息图片
  await fetchImages(1, 1) // 检测报告







})

const showSlaughterDialog = ref(false)
const slaughterFormRef = ref()
const slaughterRules = {
  batch: [{ required: true, message: '请输入批次', trigger: 'blur' }],
  weight: [{ required: true, message: '请输入到厂均重', trigger: 'blur' }],
  arrive_Time: [{ required: true, message: '请选择到厂时间', trigger: 'change' }],
  slaughtering_Time: [{ required: true, message: '请选择屠宰时间', trigger: 'change' }]
}

const slaughterDetail = reactive({
  id: 0,
  batch: '',
  weight: 0,
  arrive_Time: '',
  slaughtering_Time: '',
  createUserId: 0
})

// 在表单中使用本地时间格式
const slaughterForm = reactive({
  id: 0,
  batch: '',
  weight: 0,
  arrive_Time: '',
  slaughtering_Time: '',
  createUserId: Number(localStorage.getItem("id")) || 0
})

// 获取屠宰信息
async function fetchSlaughterInfo() {
  try {
    const res = await source.get('/api/Slaughter/SlaughterQuery', {
      params: {
        Batch: detail.value.batch
      }
    })
    if (res.data.code === 200) {
      const slaughterData = res.data.data
      // 保持原始时间格式
      const mappedData = {
        id: slaughterData.id || 0,
        batch: slaughterData.batch || '',
        weight: slaughterData.weight || 0,
        arrive_Time: slaughterData.arrive_Time || '',
        slaughtering_Time: slaughterData.slaughtering_Time || '',
        createUserId: slaughterData.createUserId || 0
      }

      Object.assign(slaughterDetail, mappedData)
      // 更新表单数据时也保持原始时间格式
      Object.assign(slaughterForm, {
        ...mappedData,
        createUserId: Number(localStorage.getItem("id")) || 0
      })
    }
  } catch (error) {
    console.error('获取屠宰信息失败:', error)
    ElMessage.error('获取屠宰信息失败')
  }
}

async function onSaveSlaughter() {
  if (!slaughterFormRef.value) return

  await slaughterFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 将本地时间转换为正确的 ISO 格式，同时保持本地时间不变
        const arrive_Time = moment(slaughterForm.arrive_Time)
          .format('YYYY-MM-DDTHH:mm:ss.SSS[Z]');
        const slaughtering_Time = moment(slaughterForm.slaughtering_Time)
          .format('YYYY-MM-DDTHH:mm:ss.SSS[Z]');

        const formData = {
          ...slaughterForm,
          batch: detail.value.batch,
          arrive_Time,
          slaughtering_Time
        }
        const res = await source.post('/api/Slaughter/SlaughterAdd', formData)

        if (res.data.code === 200) {
          ElMessage.success('保存成功')
          showSlaughterDialog.value = false
          // 刷新屠宰信息
          await fetchSlaughterInfo()
        } else {
          ElMessage.error(res.data.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存屠宰信息失败:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}

const slaughterCertList = ref<any[]>([])
function handleSlaughterCertUploadSuccess(response: any, file: any) {
  slaughterCertList.value.push(response.url)
}
// 屠宰企业信息相关
const slaughterCompany = ref({
  id: 0,
  batch: '',
  slaughter_Enterprise: '',
  founding_Time: '',
  province: '',
  city: '',
  county: '',
  company_Profile: '',
  createUserId: 0
})

const showSlaughterCompanyDialog = ref(false)
const slaughterCompanyFormRef = ref()

// 屠宰企业表单数据
const slaughterCompanyForm = ref({
  id: 0,
  slaughter_Enterprise: '',
  province: '',
  city: '',
  county: '',
  founding_Time: '',
  company_Profile: ''
})

// 地区选择相关
const slaughterRegion = ref<RegionValues>({
  province: undefined,
  city: undefined,
  area: undefined,
})

// 监听屠宰企业地区选择变化
watch(() => slaughterRegion.value, () => {
  if (slaughterRegion.value.province) {
    const { province, city, area } = slaughterRegion.value
    // 使用 v-region 的 codeToText 方法转换为文字
    slaughterCompanyForm.value.province = province || ''
    slaughterCompanyForm.value.city = city || ''
    slaughterCompanyForm.value.county = area || ''
  } else {
    slaughterCompanyForm.value.province = ''
    slaughterCompanyForm.value.city = ''
    slaughterCompanyForm.value.county = ''
  }
}, { deep: true })

// 屠宰企业表单验证规则
const slaughterCompanyRules = {
  slaughter_Enterprise: [
    { required: true, message: '请输入公司名称', trigger: 'blur' }
  ],
  founding_Time: [
    { required: true, message: '请选择成立时间', trigger: 'change' }
  ],
  company_Profile: [
    { required: true, message: '请输入公司简介', trigger: 'blur' }
  ]
}

// 保存屠宰企业信息
const onSaveSlaughterCompany = async () => {
  if (!slaughterCompanyFormRef.value) return

  await slaughterCompanyFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 确保地址相关字段有值
        const formDataToSave = {
          ...slaughterCompanyForm.value,
          batch: detail.value.batch,
          createUserId: Number(localStorage.getItem("id")),
          province: slaughterCompanyForm.value.province || '',
          city: slaughterCompanyForm.value.city || '',
          county: slaughterCompanyForm.value.county || ''
        };
        const response = await source.post('/api/Slaughter/SlaughterHouseAdd', formDataToSave)
        if (response.data.code === 200) {
          ElMessage.success('保存成功')
          showSlaughterCompanyDialog.value = false

          // 立即更新显示数据
          const savedData = {
            ...formDataToSave
          }
          Object.assign(slaughterCompany.value, savedData)

          // 重新获取最新数据
          await getSlaughterCompanyInfo()
        } else {
          ElMessage.error(response.data.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存屠宰企业信息失败:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}

// 获取屠宰企业信息
const getSlaughterCompanyInfo = async () => {
  try {

    const response = await source.get('/api/Slaughter/SlaughterHouseQuery', {
      params: {
        batch: detail.value.batch
      }
    })

    if (response.data.code === 200) {
      const data = response.data.data
      // 更新显示数据
      Object.assign(slaughterCompany.value, data)
      // 更新表单数据，用于回显
      Object.assign(slaughterCompanyForm.value, {
        id: data.id,
        slaughter_Enterprise: data.slaughter_Enterprise,
        province: data.province,
        city: data.city,
        county: data.county,
        founding_Time: data.founding_Time,
        company_Profile: data.company_Profile
      })
      // 确保使用正确的格式更新slaughterRegion
      slaughterRegion.value = {
        province: data.province || '',
        city: data.city || '',
        area: data.county || '' // 注意这里是area而不是county
      }
    }
  } catch (error) {
    console.error('获取屠宰企业信息失败:', error)
    ElMessage.error('获取企业信息失败')
  }
}

// 打开设置弹窗时，确保数据正确回显
const openSlaughterCompanyDialog = () => {
  // 如果有现有数据，复制到表单中
  if (slaughterCompany.value) {
    Object.assign(slaughterCompanyForm.value, {
      slaughter_Enterprise: slaughterCompany.value.slaughter_Enterprise,
      province: slaughterCompany.value.province,
      city: slaughterCompany.value.city,
      county: slaughterCompany.value.county,
      founding_Time: slaughterCompany.value.founding_Time,
      company_Profile: slaughterCompany.value.company_Profile
    })
    // 设置地区选择器的值
    slaughterRegion.value = {
      province: slaughterCompany.value.province,
      city: slaughterCompany.value.city,
      area: slaughterCompany.value.county
    }
  }
  showSlaughterCompanyDialog.value = true
}

const slaughterCompanyPhotoList = ref<any[]>([])
function handleSlaughterCompanyPhotoUploadSuccess(response: any, file: any) {
  slaughterCompanyPhotoList.value.push(response.url)
}

// ================== 深加工信息 ==================
const processDetail = reactive({
  id: 0,
  batch: '',
  principal: '',    // 负责人
  responsible_Team: '',  // 班组
  createUserId: 0
})
const showProcessDialog = ref(false)
const processForm = reactive({
  principal: '',
  responsible_Team: ''
})
const processFormRef = ref()
const processRules = {
  responsible_Team: [{ required: true, message: '请输入班组', trigger: 'blur' }],
  principal: [{ required: true, message: '请输入负责人', trigger: 'blur' }]
}
const processFoodSafeList = ref<any[]>([])
function handleProcessFoodSafeUploadSuccess(response: any, file: any) {
  processFoodSafeList.value.push(response.url)
}

// 保存深加工信息
async function onSaveProcess() {
  if (!processFormRef.value) return;

  processFormRef.value.validate(async (valid: any) => {
    if (valid) {
      try {
        const formData = {
          id: processDetail.id || 0,
          batch: detail.value.batch,
          principal: processForm.principal,
          responsible_Team: processForm.responsible_Team,
          createUserId: Number(localStorage.getItem("id"))
        };

        const response = await source.post('/api/Deep/DeepProcessingAdd', formData);

        if (response.data.code === 200) {
          ElMessage.success('保存成功');
          showProcessDialog.value = false;

          // 立即更新显示数据
          const savedData = {
            ...formData,
            id: response.data.data?.id || processDetail.id
          };
          Object.assign(processDetail, savedData);

          // 重新获取最新数据
          await fetchProcessDetail();
        } else {
          ElMessage.error(response.data.msg || '保存失败');
        }
      } catch (error) {
        console.error('保存深加工信息失败:', error);
        ElMessage.error('保存失败');
      }
    }
  });
}

// 获取深加工信息
const fetchProcessDetail = async () => {
  try {
    const response = await source.get('/api/Deep/DeepProcessingQuery', {
      params: {
        Batch: detail.value.batch
      }
    });

    if (response.data.code === 200) {
      const data = response.data.data;
      if (data) {
        // 更新显示数据
        Object.assign(processDetail, {
          id: data.id || 0,
          batch: data.batch || '',
          principal: data.principal || '',
          responsible_Team: data.responsible_Team || '',
          createUserId: data.createUserId || 0
        });

        // 更新表单数据，用于回显
        Object.assign(processForm, {
          principal: data.principal || '',
          responsible_Team: data.responsible_Team || ''
        });
      }
    }
  } catch (error) {
    console.error('获取深加工信息失败:', error);
    ElMessage.error('获取深加工信息失败');
  }
};

// 供应商信息
const processSuppliers = ref<Array<{ label: string; batch: string; materials: any[] }>>([
  { label: '原料', batch: '', materials: [] },
  { label: '辅料', batch: '', materials: [] },
  { label: '添加剂', batch: '', materials: [] },
  { label: '包装', batch: '', materials: [] }
])
const showSupplierDialog = ref(false)
const supplierDialogTitle = ref('')
const supplierForm = reactive({ batch: '' })
const supplierFormRef = ref()
const supplierRules = {
  batch: [{ required: true, message: '请输入生产批次', trigger: 'blur' }]
}
let currentSupplierIdx = 0
function openSupplierDialog(idx: number) {


  currentSupplierIdx = idx
  supplierDialogTitle.value = `供应商信息-${processSuppliers.value[idx].label}`


  supplierForm.batch = detail.value.batch;
  showSupplierDialog.value = true
}
function onSaveSupplier() {
  supplierFormRef.value.validate((valid: any) => {
    if (valid) {
      processSuppliers.value[currentSupplierIdx].batch = supplierForm.batch
      showSupplierDialog.value = false

    }
  })
}
function handleSupplierMaterialUploadSuccess(idx: number, response: any) {
  processSuppliers.value[idx].materials.push(response.url)
}
// 深加工企业信息
const showProcessingPlantDialog = ref(false)
const processingPlant = reactive({
  id: 0,
  batch: '',
  deep_Enterprise: '',
  production_Permit: '',
  createUserId: 0
})

const processingPlantForm = reactive({
  deep_Enterprise: '',
  production_Permit: ''
})

const processingPlantFormRef = ref()
const processingPlantRules = {
  deep_Enterprise: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  production_Permit: [{ required: true, message: '请输入生产许可证号', trigger: 'blur' }]
}

// 保存深加工企业信息
function onSaveProcessingPlant() {
  if (!processingPlantFormRef.value) return;

  processingPlantFormRef.value.validate(async (valid: any) => {
    if (valid) {
      try {
        const formData = {
          ...processingPlantForm,
          id: processingPlant.id || 0,
          batch: detail.value.batch,
          createUserId: Number(localStorage.getItem("id"))
        };

        const response = await source.post('/api/Deep/ProcessingPlantAdd', formData);

        if (response.data.code === 200) {
          ElMessage.success('保存成功');
          showProcessingPlantDialog.value = false;

          // 立即更新显示数据
          const savedData = {
            ...processingPlantForm,
            id: response.data.data?.id || processingPlant.id,
            batch: detail.value.batch,
            createUserId: Number(localStorage.getItem("id"))
          };
          Object.assign(processingPlant, savedData);

          // 重新获取最新数据
          await fetchProcessingPlant();
        } else {
          ElMessage.error(response.data.msg || '保存失败');
        }
      } catch (error) {
        console.error('保存深加工企业信息失败:', error);
        ElMessage.error('保存失败');
      }
    }
  });
}

// 获取深加工企业信息
const fetchProcessingPlant = async () => {
  try {
    const response = await source.get('/api/Deep/ProcessingPlantQuery', {
      params: {
        Batch: detail.value.batch
      }
    });

    if (response.data.code === 200) {
      const data = response.data.data;
      if (data) {
        // 更新显示数据
        Object.assign(processingPlant, {
          id: data.id || 0,
          batch: data.batch || '',
          deep_Enterprise: data.deep_Enterprise || '',
          production_Permit: data.production_Permit || '',
          createUserId: data.createUserId || 0
        });

        // 更新表单数据，用于回显
        Object.assign(processingPlantForm, {
          deep_Enterprise: data.deep_Enterprise || '',
          production_Permit: data.production_Permit || ''
        });
      }
    }
  } catch (error) {
    console.error('获取深加工企业信息失败:', error);
    ElMessage.error('获取企业信息失败');
  }
};

const processCompanyPhotoList = ref<any[]>([])
function handleProcessCompanyPhotoUploadSuccess(response: any, file: any) {
  processCompanyPhotoList.value.push(response.url)
}

const farmingReportList = ref<any[]>([])
const farmingAnimalCertList = ref<any[]>([])
const farmingCompanyPhotoList = ref<any[]>([])
function handleFarmingReportUploadSuccess(response: any, file: any) {
  farmingReportList.value.push(response.url)
}
function handleFarmingAnimalCertUploadSuccess(response: any, file: any) {
  farmingAnimalCertList.value.push(response.url)
}
function handleFarmingCompanyPhotoUploadSuccess(response: any, file: any) {
  farmingCompanyPhotoList.value.push(response.url)
}
//养殖信息保存
function onSaveFarming() {
  if (!farmingFormRef.value) return;

  farmingFormRef.value.validate((valid: any) => {
    if (valid) {
      // TODO: 保存养殖信息接口

      const formData = {
        ...farmingDetail.value,
        batch: detail.value.batch,
        createUserId: Number(localStorage.getItem("id"))
      };
      source.post("/api/Aquaculture/AquacultureAdd", formData)
        .then(res => {
          if (res.data.code == 200) {
            ElMessage.success(res.data.msg);
            showFarmingDialog.value = false
            fetchFarmingInfo()
          }
          else {
            ElMessage.error(res.data.msg);
          }
        })

      Object.assign(farmingDetail.value, farmingForm.value)
    }
  })
}

// 计算属性：表格数据
const tableData = computed(() => {
  return healthList.value;
});

// 保存新行
async function onSaveNewRow(row: any) {
  if (!isValidRow(row)) {
    ElMessage.warning('请填写完整信息');
    return;
  }

  try {
    const res = await source.post('/api/Aquaculture/HealthcareAdd', {
      batch: detail.value.batch,
      feeding_Date: Number(row.feeding_Date),
      health_Products: row.health_Products,
      healthcare_Methods: row.healthcare_Methods,
      createUserId: Number(localStorage.getItem("id"))
    });

    if (res.data.code === 200) {
      // 更新行数据
      const index = healthList.value.findIndex(item => item === row);
      if (index !== -1) {
        // 使用数组方法触发响应式更新
        const newRow = {
          id: res.data.data.id, // 确保保存返回的ID
          feeding_Date: Number(row.feeding_Date),
          health_Products: row.health_Products,
          healthcare_Methods: row.healthcare_Methods,
          editing: false,
          isNew: false // 移除新行标记
        };
        healthList.value.splice(index, 1, newRow);
      }
      ElMessage.success('添加成功');
      // 重新获取列表以确保数据同步
      await fetchHealthList();
    } else {
      ElMessage.error(res.data.msg || '添加失败');
    }
  } catch (error) {
    console.error('添加保健信息失败:', error);
    ElMessage.error('添加失败');
  }
}

// 取消新行
function onCancelNewRow(index: number) {
  healthList.value.splice(index, 1);
}

// 定义图片数据接口
interface PictureItem {
  id: number;          // 图片记录ID
  pictureURL: string;  // 图片URL
  displayUrl: string;  // 实际显示的URL
}

// 存储不同类型的图片组
const imageGroups = reactive<{ [key: string]: PictureItem[] }>({})

// 生成图片组的key
function getImageKey(sourceType: number, stageType: number) {
  return `${sourceType}-${stageType}`
}

// 获取图片列表
async function fetchImages(sourceType: number, stageType: number) {
  try {
    const res = await source.get("/api/Picture/PictureGet", {
      params: {
        Batch: detail.value.batch,
        SourceType: sourceType,
        StageType: stageType
      }
    })

    if (res.data.code === 200) {
      const key = getImageKey(sourceType, stageType)
      imageGroups[key] = [] // 初始化数组

      // 处理每张图片
      await Promise.all(res.data.data.map(async (item: any) => {
        try {


          // 获取可访问的URL
          const urlRes = await fileUpload.get("/api/File/GetImageUrl", {
            params: {
              objectName: item.pictureURL
            }
          })

          if (urlRes.data) {
            // 保存完整的图片信息
            imageGroups[key].push({
              id: item.id,           // 保存图片ID
              pictureURL: item.pictureURL,
              displayUrl: urlRes.data // 实际显示的URL
            })


          }
        } catch (error) {
          console.error('获取图片URL失败:', error)
        }
      }))
    }
  } catch (error) {
    console.error('获取图片列表失败:', error)
  }
}

// 删除图片
async function handleDeleteImage(sourceType: number, stageType: number, index: number, imageId: number) {
  try {
    // 调用删除API
    const res = await source.post("/api/Picture/PictureDel", null, {
      params: {
        Id: imageId
      }
    })

    if (res.data.code === 200) {
      // 从界面移除图片
      const key = getImageKey(sourceType, stageType)
      imageGroups[key].splice(index, 1)
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除图片失败:', error)
    ElMessage.error('删除失败，请重试')
  }
}

// 处理文件上传
const handleImageChange = async (uploadFile: UploadFile, sourceType: number, stageType: number) => {
  const key = getImageKey(sourceType, stageType)
  if (!imageGroups[key]) {
    imageGroups[key] = []
  }

  if (imageGroups[key].length >= 9) {
    ElMessage.warning('最多只能上传9张图片')
    return
  }

  const formData = new FormData()
  const file = uploadFile.raw // 获取原始文件
  if (file) {
    formData.append('file', file)
  }

  try {
    // 添加图片记录
    const pictureData = {
      batch: detail.value.batch,
      sourceType: sourceType,
      stageType: stageType.toString(),
      pictureURL: uploadFile.name,
      createUserId: Number(localStorage.getItem("id"))
    }

    const addRes = await source.post("/api/Picture/PictureAdd", pictureData)

    if (addRes.data.code === 200) {
      // 先上传文件
      await fileUpload.post('/api/File/UploadFile', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })

      // 获取可访问的URL
      const urlRes = await fileUpload.get("/api/File/GetImageUrl", {
        params: {
          objectName: uploadFile.name
        }
      })

      if (urlRes.data) {
        // 添加新图片到列表
        imageGroups[key].push({
          id: addRes.data.data.id, // 使用返回的图片ID
          pictureURL: uploadFile.name,
          displayUrl: urlRes.data
        })

        await fetchImages(sourceType, stageType) // 检测报告
        ElMessage.success('图片上传成功')
      }
    } else {
      ElMessage.error(addRes.data.msg || '添加图片记录失败')
    }
  } catch (error) {
    console.error('Upload error:', error)
    ElMessage.error('上传失败，请重试')
  }
}

//显示头顶数据据和图片
const TracebackDetail = async () => {
  const id = route.query.id;
  const res = await source.get("/api/Management/TracebackListDelete", { params: { id } });
  detail.value = res.data.data;
  if (detail.value.url) {
    const imgRes = await fileUpload.get("/api/File/GetImageUrl", {
      params: { objectName: detail.value.url }
    });
    detail.value.url = imgRes.data;
  }
};

// 添加refreshAddress方法确保slaughterRegion正确设置
function refreshAddress() {
  // 刷新数据
  getSlaughterCompanyInfo();
}

// 监听slaughterRegion变化，用于调试
watch(() => slaughterRegion.value, (newVal) => {
  console.log('slaughterRegion变化:', newVal);
}, { deep: true })
</script>

<style scoped>
.trace-detail-view {
  max-width: 1200px;
  margin: 0 auto;
  background: #fff;
  padding: 24px;
  border-radius: 8px;
}

.header {
  display: flex;
  align-items: flex-start;
  gap: 24px;
  margin-bottom: 24px;
}

.cover {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid #eee;
}

.base-info {
  flex: 1;
}

.title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.info-row {
  margin-top: 12px;
  color: #666;
  display: flex;
  gap: 32px;
}

.section {
  margin-bottom: 32px;
}

.section-title {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.report-list {
  display: flex;
  align-items: center;
  gap: 16px;
}

.report-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #eee;
}

.upload-btn {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background: #fafafa;
  cursor: pointer;
}

.edit-row {
  display: flex;
  align-items: center;
  margin-top: 12px;
  gap: 8px;
}

.image-upload-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.image-uploader {
  display: flex;
  align-items: center;
}

.image-upload-box {
  width: 120px;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background: #fafafa;
}

.image-upload-box:hover {
  border-color: #409EFF;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 12px;
  color: #8c939d;
}

.image-preview {
  width: 116px;
  height: 116px;
  object-fit: cover;
  border-radius: 4px;
}

.image-item {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 6px;
  overflow: hidden;
}

.image-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  top: 0;
  right: 0;
  padding: 4px;
  background-color: rgba(0, 0, 0, 0.5);
  border-bottom-left-radius: 6px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-item:hover .image-actions {
  opacity: 1;
}

.delete-icon {
  color: #fff;
  font-size: 18px;
  cursor: pointer;
}

.delete-icon:hover {
  color: #f56c6c;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.add-btn {
  margin-right: 12px;
}

.badge {
  background-color: #909399;
  color: white;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 8px;
}

.new-row-form {
  margin-top: 16px;
  display: flex;
  gap: 12px;
  align-items: center;
  background-color: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
}

.form-buttons {
  display: flex;
  gap: 8px;
}

:deep(.el-button--link) {
  padding: 0 8px;
}

:deep(.el-input__wrapper) {
  border-radius: 2px;
}

:deep(.el-table__append-wrapper) {
  .el-input {
    width: 100%;
  }
}

.empty-block {
  padding: 32px 0;
  text-align: center;
}

.empty-text {
  color: #909399;
  font-size: 14px;
  margin-right: 16px;
}

.add-row-button {
  margin-top: 16px;
  text-align: center;
}

.no-border :deep(.el-input__wrapper) {
  box-shadow: none !important;
  background: transparent;
}

.no-border :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset !important;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.health-info-header {
  margin-bottom: 16px;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 8px;
}

.title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.add-button {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  color: #606266;
  font-size: 14px;
  padding: 4px 12px;
  border-radius: 4px;
  transition: all 0.3s;
}

.add-button:hover {
  background: #f5f7fa;
}

.badge {
  background: #909399;
  color: white;
  border-radius: 50%;
  min-width: 18px;
  height: 18px;
  padding: 0 6px;
  font-size: 12px;
  line-height: 18px;
  text-align: center;
  display: inline-block;
}

.action-group {
  display: flex;
  align-items: center;
  gap: 4px;
}

.action-number {
  width: 16px;
  height: 16px;
  background: #909399;
  color: white;
  border-radius: 50%;
  font-size: 12px;
  line-height: 16px;
  text-align: center;
}

:deep(.el-table__header) {
  margin: 0 !important;
}

:deep(.el-table__header-wrapper) {
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
  overflow: hidden;
}

:deep(.el-table) {
  border-radius: 4px;
  overflow: hidden;
}

.image-container {
  width: 100%;
  overflow: hidden;
}
</style>